package com.epam.iunna.bookshop.controller.actions;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.epam.iunna.bookshop.controller.application.Constants;
import com.epam.iunna.bookshop.controller.filters.AuthFilter;
import com.epam.iunna.bookshop.controller.utils.dispatch.ActionInt;
import com.epam.iunna.bookshop.model.User;
import com.epam.iunna.bookshop.model.UserDao;
import com.epam.iunna.bookshop.model.service.BasketBean;

public class Buy  implements ActionInt{

    @Override
    public String perform(HttpServletRequest request,
            HttpServletResponse response) {
        try{
         
            String address = request.getParameter("addressDelivery");
            String notes = request.getParameter("notes");
            
            Map<String,String> errorMap = new HashMap<String,String>();
            
            //validation
            if( address.isEmpty() ){
                errorMap.put("addressDelivery", " * required");
            }
            if( !errorMap.isEmpty() ){
                request.setAttribute("errorMap", errorMap);
                return "/orderItems.jsp";
            }
            
            
            
            BasketBean basketBean = (BasketBean) request.getSession().getAttribute(BasketBean.BASKET_BEAN_SESSION_BEAN);
            if( basketBean == null ){
                System.out.println("Basket is not avaliable in session for buying");
                return Constants.FATAL_ERROR_PAGE_PATH;
            }
            basketBean.getOrder().setAddress(address);
            basketBean.getOrder().setNotes(notes);
            
            String returnPage="/boughtErr.jsp";
            User user = (User)request.getSession().getAttribute( AuthFilter.USER_SESSION_KEY );
            BigDecimal money = user.getMoney();
            if( basketBean.getTotalCost().compareTo( money ) == -1 ){
                user.setMoney( money.add(basketBean.getTotalCost().multiply(new BigDecimal("-1"))) );
                basketBean.getOrder().setPaymentStatus(true);
                UserDao userDao = new UserDao();
                userDao.updateMoney(user);
                returnPage = "/boughtSucc.jsp";
            }
            
            
            basketBean.saveOrder();
            
            request.getSession().setAttribute(BasketBean.BASKET_BEAN_SESSION_BEAN,null);
            return returnPage;
            
        }catch(SQLException e){
            System.out.println("Db error ");
            e.printStackTrace();
            return Constants.FATAL_ERROR_PAGE_PATH;
        }
    }

}
